package com.tiger.userClient;



import org.apereo.cas.client.authentication.AuthenticationFilter;
import org.apereo.cas.client.session.SingleSignOutFilter;
import org.apereo.cas.client.session.SingleSignOutHttpSessionListener;
import org.apereo.cas.client.util.HttpServletRequestWrapperFilter;
import org.apereo.cas.client.validation.Cas30ProxyReceivingTicketValidationFilter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;

import java.util.EventListener;
import java.util.HashMap;
import java.util.Map;

/**
 *  CAS过滤器：配置过滤器到springboot
 */
@Configuration
public class CasFilterConfig {

    @Value("${cas.server-url-prefix}")
    private String serverUrlPrefix;
    @Value("${cas.server-login-url}")
    private String serverLoginUrl;
    @Value("${cas.client-host-url}")
    private String clientHostUrl;

    /**
     * 添加监听器
     */
    @Bean
    public ServletListenerRegistrationBean<EventListener> singleSignOutListenerRegistration() {
        ServletListenerRegistrationBean<EventListener> registrationBean = new ServletListenerRegistrationBean<EventListener>();
        registrationBean.setListener(new SingleSignOutHttpSessionListener());
        registrationBean.setOrder(Ordered.HIGHEST_PRECEDENCE);
        return registrationBean;
    }

    /**
     * 配置过滤验证器 这里用的是Cas30ProxyReceivingTicketValidationFilter
     */
    @Bean
    public FilterRegistrationBean filterValidationRegistration() {
        final FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(new Cas30ProxyReceivingTicketValidationFilter());
        //设定匹配的路径
        registration.addUrlPatterns("/proxyCallback","/*");

        Map<String, String> initParameters = new HashMap<String, String>();
        // cas 服务地址，从后台请求CAS服务，得到ticket信息（内部通讯）
        initParameters.put("casServerUrlPrefix", serverUrlPrefix);
        // 验证ticket正确后，对当前请求重定向一次的服务地址（主要消除地址中的ticket参数），代理服务的请求（内部通讯）或客户端请求都会处理。可由参数redirectAfterValidation设置不重定向
        initParameters.put("serverName", clientHostUrl);
        // 是否对serviceUrl进行编码，默认true：设置false可以在302对URL跳转时取消显示;jsessionid=xxx的字符串
        initParameters.put("encodeServiceUrl","false");
        initParameters.put("encoding", "UTF-8");

        //****************代理端配置和被代理端配置都开启了表示该项目既可以作为代理端也可以作为被代理端**************************
        // 代理模式(代理端)
        // 发送给CAS服务器，用于代理验证后的回调地址（内部通讯）
        //initParameters.put("proxyCallbackUrl",clientHostUrl+"/proxyCallback");
        // 代理验证请求地址后缀，与proxyCallbackUrl中设置的一致。用于拦截验证回调
        //initParameters.put("proxyReceptorUrl","/proxyCallback");
        // 代理模式(被代理端)
        //initParameters.put("acceptAnyProxy","true");
        //initParameters.put("redirectAfterValidation","false");
        registration.setInitParameters(initParameters);
        // 设定加载的顺序
        registration.setOrder(1);
        return registration;
    }

    /**
     *    配置登录过滤器(过滤器顺序有要求，先登录-》授权过滤器-》配置过滤验证器-》wraper过滤器)
     */
    @Bean
    public FilterRegistrationBean filterSingleRegistration() {
        final FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(new SingleSignOutFilter());
        // 设定匹配的路径
        registration.addUrlPatterns("/*");
        Map<String, String> initParameters = new HashMap<String, String>();
        initParameters.put("casServerUrlPrefix", serverUrlPrefix);
        registration.setInitParameters(initParameters);
        registration.setName("CAS Single Sign Out Filter");
        // 设定加载的顺序
        registration.setOrder(2);
        return registration;
    }

    /**
     *    配置授权过滤器
     */
    @Bean
    public FilterRegistrationBean filterAuthenticationRegistration() {

        System.out.println("金色cas filter 拦截登陆 filterAuthenticationRegistration");


        final FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(new AuthenticationFilter());
        // 设定匹配的路径
        //registration.addUrlPatterns("/*");
        registration.addUrlPatterns("/auth/auth");
        Map<String, String> initParameters = new HashMap<String, String>();
        initParameters.put("casServerLoginUrl", serverLoginUrl);
        initParameters.put("serverName", clientHostUrl);

        registration.setInitParameters(initParameters);
        // 设定加载的顺序
        registration.setOrder(3);
        return registration;
    }

    /**
     * request wraper过滤器
     */
    @Bean
    public FilterRegistrationBean filterWrapperRegistration() {
        final FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(new HttpServletRequestWrapperFilter());
        // 设定匹配的路径
        registration.addUrlPatterns("/*");
        registration.setName("CAS HttpServletRequest Wrapper Filter");
        // 设定加载的顺序
        registration.setOrder(5);
        return registration;
    }
}

